<template>
  <basic-dialog
    title="关联归类名称"
    width="60%"
    :visible="dialogVisible"
    :showFooter="false"
    :handleClose="handleClose"
  >
    <basic-form
      ref="formData"
      :isScalingBtn="false"
      :formColumns="formItemList"
      :dataSource="formData"
      :handleSearchForm="handleSearch"
      :hasQueryPermission="false"
      @getFormData="getFormData"
    >
      <el-row slot="extensionActions" type="flex">
        <el-button
          v-if="isNotLinked()"
          type="primary"
          @click="handleBatchLinked"
        >批量关联</el-button>
        <el-button
          v-if="isLinked()"
          @click="handleBatchCanceled"
        >批量取消</el-button>
        <el-button type="primary" @click="handleOk">确定</el-button>
      </el-row>
    </basic-form>
    <el-tabs v-model="tabs.current" @tab-click="handleSwitchTabs">
      <el-tab-pane label="已关联" :name="tabs.nameList[1]"></el-tab-pane>
      <el-tab-pane label="未关联" :name="tabs.nameList[0]"></el-tab-pane>
    </el-tabs>
    <BasicTable
      showActionCol
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :pagination="pagination"
      :pageSizes="pageSizes"
      :tableHeight="480"
      :actionRender="renderTableBtnAction"
      :selectionChange="handleSelectionChange"
      @pageChange="handlePageChange"
      @pageSizeChange="handlePageSizeChange"
    />
  </basic-dialog>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import BasicDialog from '@/components/BasicDialog';
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import { isResponseSuccess } from '@/utils/bizUtils';
import { getArraysByMaps, getListByMapDimensionKey } from '@/utils/getUtils';
export default {
  components: {
    BasicDialog,
    BasicForm,
    BasicTable
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
  },
  data () {
    return {
      categoryUuid: this.$attrs.categoryUuid,
      dialogVisible: false,
      formItemList: [
        { prop: 'classificationName', label: '归类名称', type: 'input' },
        { prop: 'taxCateName', label: '税类名称', type: 'input' },
        { prop: 'taxCateNo', label: '税类编码', type: 'input' }
      ],
      formData: {
        classificationName: '', // 归类名称
        taxCateName: '', // 税类名称
        taxCateNo: '' // 税类编码
      },
      tabs: {
        current: 'linked', // 当前tabs页签
        nameList: ['notLinked', 'linked'] // tabs页签key集合
      },
      tableInfo: {
        list: [],
        selection: [],
        columns: [
          { title: '归类名称', key: 'classificationName' },
          { title: '税类名称', key: 'taxCateName' },
          { title: '税类编码', key: 'taxCateNo' },
          { title: '税率', key: 'taxRate' },
          { title: '审核状态', key: 'state' },
          { title: '描述', key: 'note' },
        ],
        loading: false,
        cacheLinked: new Map(), // 缓存已关联表格数据
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 20, 30, 40],
      apiObj: {
        getRelByCondition: { // 已关联
          url: '/sysback/classification/getRelByCondition',
          type: 'post'
        },
        getNotRelByCondition: { // 未关联
          url: '/sysback/classification/getNotRelByCondition',
          type: 'post'
        }
      }
    }
  },
  mounted () {
    this.setLinkedMapsByInit();
  },
  watch: {
    visible (val) {
      this.dialogVisible = val;
      if (val) { this.handleSearch(); }
    }
  },
  methods: {
    // 是已关联
    isLinked () {
      return this.tabs.current === this.tabs.nameList[1];
    },
    // 是未关联
    isNotLinked () {
      return this.tabs.current === this.tabs.nameList[0];
    },
    // 数据为空
    isEmptyForCurrentList (list = this.tableInfo.list) {
      return list?.length === 0;
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const linkBtn = <el-button
        type="text"
        onClick={() => { this.handleLinked(row) }}
      >关联</el-button>
      const cancelBtn = <el-button
        type="text"
        onClick={() => { this.handleCanceled(row) }}
      >取消</el-button>
      if (this.isLinked()) {
        return (<div class="table-action">{cancelBtn}</div>);
      }
      if (this.isNotLinked()) {
        return (<div class="table-action">{linkBtn}</div>);
      }
      return <div class="table-action"></div>;
    },
    // 表单查询
    handleSearch () {
      this.pagination.nowPage = 1;
      this.getTableDataBySearchForm();
    },
    // 表格数据勾选或勾选取消
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableDataBySearchForm();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableDataBySearchForm();
    },
    // 关闭弹框
    handleClose () {
      this.$emit('update:visible', false);
    },
    // 确定
    handleOk () {
      this.$emit('getClassificationInfo', {
        classificationNames: getListByMapDimensionKey(
          this.tableInfo.cacheLinked, 'classificationName'
        ).join(';'),
        classificationUuids: getListByMapDimensionKey(this.tableInfo.cacheLinked)
      });
      this.resetDialogState();
    },
    // 切换tabs
    handleSwitchTabs () {
      this.getTableDataBySearchForm();
    },
    // 关联
    handleLinked (row) {
      this.setMapByLinked(row);
      this.getTableDataBySearchForm();
      this.$message.success('关联成功');
    },
    // 取消关联
    handleCanceled (row) {
      this.deleteMapByCanceled(row);
      this.getTableDataBySearchForm();
      this.$message.success('取消成功');
    },
    // 批量关联
    handleBatchLinked () {
      if (this.isEmptyForCurrentList(this.tableInfo.selection)) {
        return this.$message.warning('请勾选表格后再操作');
      }
      this.tableInfo.selection.forEach(row => {
        this.setMapByLinked(row);
      });
      this.getTableDataBySearchForm();
      this.$message.success('批量关联成功');
    },
    // 批量取消
    handleBatchCanceled () {
      if (this.isEmptyForCurrentList(this.tableInfo.selection)) {
        return this.$message.warning('请勾选表格后再操作');
      }
      this.tableInfo.selection.forEach(row => {
        this.deleteMapByCanceled(row);
      });
      this.getTableDataBySearchForm();
      this.$message.success('批量取消成功');
    },
    // 关联 - 给map缓存设置新值
    setMapByLinked (row, key = 'uuid') {
      this.tableInfo.cacheLinked.set(row[key], row);
    },
    // 取消 - 给map缓存删除当前值
    deleteMapByCanceled (row, key = 'uuid') {
      this.tableInfo.cacheLinked.delete(row[key], row);
    },
    // 重置弹框状态
    resetDialogState () {
      this.$emit('update:visible', false);
      this.tableInfo.list = [];
      this.pagination = {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      }
      this.tabs.current = this.tabs.nameList[1];
    },
    // 获取表单内容
    getFormData (data) {
      this.formData = data;
    },
    // 获取查询通用入参
    getCommonParamsBySearch () {
      const { nowPage, pageShow } = this.pagination;
      return {
        nowPage,
        pageShow,
        ...this.formData,
        sortName: '',
        sortType: ''
      }
    },
    // 获取表格数据
    getTableDataBySearchForm () {
      if (this.isLinked() && (this.isEmptyForCurrentList(
        getArraysByMaps(this.tableInfo.cacheLinked)
      ))) {
        this.tableInfo.list = [];
        return false;
      }
      const { getRelByCondition, getNotRelByCondition } = this.apiObj;
      const { url, type } = this.isLinked() ? getRelByCondition : getNotRelByCondition;
      this.postRequestTableData({
        url: `${url}?categoryUuid=${this.categoryUuid}`,
        type,
        data: {
          ...this.getCommonParamsBySearch(),
          relClassificationUuids: getListByMapDimensionKey(this.tableInfo.cacheLinked)
        }
      }).then(retData => {
        this.tableInfo.list = retData.results;
        this.pagination.totalNum = retData.totalNum;
      });
    },
    // 设置已关联map集合 初始化的时候
    setLinkedMapsByInit () {
      if (this.isNotLinked()) { return false; }
      if (this.isEmptyForCurrentList(this.$attrs.relClassificationUuids)) { return false; }
      const { url, type } = this.apiObj.getRelByCondition;
      this.postRequestTableData({
        url: `${url}?categoryUuid=${this.categoryUuid}`,
        type,
        data: {
          ...this.getCommonParamsBySearch(),
          relClassificationUuids: this.$attrs?.relClassificationUuids
        }
      }).then(retData => {
        retData.results.forEach(row => {
          this.setMapByLinked(row);
        });
      });
    },
    // 获取表格数据post请求
    async postRequestTableData ({ url, type, data = {}, isFormData = false }) {
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
  }
}
</script>
<style lang="less" scoped>
</style>
